package com.dht.xiao.jianye.activity_bed;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.dht.xiao.jianye.R;
import com.dht.xiao.jianye.base.BaseActivity;
import com.dht.xiao.jianye.bean.EndReadBean;
import com.dht.xiao.jianye.bean.SimpleBean;
import com.dht.xiao.jianye.bean.newdata.DepartmentsBean;
import com.dht.xiao.jianye.bean.newdata.HospitalBean;
import com.dht.xiao.jianye.bean.newdata.ProductListBean;
import com.dht.xiao.jianye.bean.newdata.SpecListBean;
import com.dht.xiao.jianye.bean.newdata.UserBean;
import com.dht.xiao.jianye.dialog.DoResultDialog;
import com.dht.xiao.jianye.http.MainHttp;
import com.dht.xiao.jianye.utils.Constants;
import com.licheedev.myutils.LogPlus;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.reactivestreams.Subscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import cn.dlc.commonlibrary.ui.widget.CommonItemView;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.ui.widget.popup.CommonPopupList;
import cn.dlc.commonlibrary.utils.ToastUtil;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class BindTagActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.item_rfid_amount)
    CommonItemView mItemRfidAmount;
    //@BindView(R.id.item_name)
    //CommonItemView mItemName;
    @BindView(R.id.tv_spec)
    TextView mTvSpec;
    @BindView(R.id.drop_spec)
    FrameLayout mDropSpec;
    @BindView(R.id.item_spec)
    CommonItemView mItemSpec;
    @BindView(R.id.btn_bind)
    Button mBtnBind;

    @BindView(R.id.tv_user)
    TextView mTvUser;
    @BindView(R.id.drop_user)
    FrameLayout mDropUser;
    @BindView(R.id.item_user)
    CommonItemView mItemUser;
    @BindView(R.id.tv_departments)
    TextView mTvDepartments;
    @BindView(R.id.drop_departments)
    FrameLayout mDropDepartments;
    @BindView(R.id.item_departments)
    CommonItemView mItemDepartments;
    @BindView(R.id.tv_Hospital)
    TextView mTvHospital;
    @BindView(R.id.drop_Hospital)
    FrameLayout mDropHospital;
    @BindView(R.id.item_Hospital)
    CommonItemView mItemHospital;
    
    @BindView(R.id.tv_productName)
    TextView mTvProductName;
    @BindView(R.id.drop_product)
    FrameLayout mDropProduct;


    public static final String EXTRA_RFIDS = "rfids";
    private CommonPopupList mSpecPopup;//分类规格
    private CommonPopupList mProductPopup;//产品
    private CommonPopupList mHospitalPopup;//医院
    private CommonPopupList mUserPopup;//个人
    private CommonPopupList mDepartmentsPopup;//科室

    private String mRfids;

    List<SpecListBean.DataBean> specList;
    private Integer specId = null;

    List<ProductListBean.DataBean> productList;
    private Integer productId = null;

    List<HospitalBean.DataBean> HospitalList;
    private Integer HospitalId = null;

    List<DepartmentsBean.DataBean> DepartmentsList;
    private Integer DepartmentsId = null;

    List<UserBean.DataBean> UserList;
    private Integer UserId = 0;

    private Integer MerchantId = null;
    String ANDROID_ID;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_tag;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //resovleIntent();
        mTitleBar.leftExit(this);
       // mItemRfidAmount.setContent(String.valueOf(mRfids.size()));
        initView();
        initPopupList();
       // initDepartments();
        initHospitalList();
       // initUser();
        getMachineCode();
    }
    private void getMachineCode() {
        ANDROID_ID =
                Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        if (TextUtils.isEmpty(ANDROID_ID)) {
            ANDROID_ID = Build.SERIAL;
        }
        LogPlus.e("ANDROID_ID =" + ANDROID_ID);
        beginRead(ANDROID_ID);
    }


    @OnClick({ R.id.drop_spec, R.id.btn_bind, R.id.drop_departments,R.id.drop_Hospital, R.id.drop_user })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_spec:
                mSpecPopup.showAsDropDown(view);
                break;
            case R.id.drop_Hospital:
                mHospitalPopup.showAsDropDown(view);
                break;
            case R.id.drop_user:
                mUserPopup.showAsDropDown(view);
                break;
            case R.id.drop_departments:
                mDepartmentsPopup.showAsDropDown(view);
                break;
            case R.id.btn_bind:
                doBind();
                break;
        }
    }

    private void resovleIntent() {
        Intent intent = getIntent();
        //mRfids = intent.getStringArrayListExtra(EXTRA_RFIDS);
    }

    private void beginRead(String series) {

        MainHttp.get().beginRead(series,"0")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        delaytime();
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }
    private void delaytime() {
        showWaitingDialog("正在读取",true);
        Observable.timer(5, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        dismissWaitingDialog();
                        endRead(ANDROID_ID);
                    }
                });

    }
    private void endRead(String series) {
        MainHttp.get().endRead(series,"3","0","")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<EndReadBean>() {
                    @Override
                    public void onSuccess(EndReadBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        LogPlus.e("rfids="+hotelBean.data.rfids);
                        if (!TextUtils.isEmpty(hotelBean.data.rfids)) {
                            mRfids = hotelBean.data.rfids;
                            List<String> list = Arrays.asList(mRfids.split(","));
                            mItemRfidAmount.setContent(String.valueOf(list.size()));
                        }else {
                            ToastUtil.show(getActivity(),"RFID为空");
                        }
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    /**
     * 开始绑定
     */
    private void doBind() {

        if (productId == null) {
            showToast("请选择产品!");
            return;
        }
        if (DepartmentsId == null) {
            showToast("请选择科室!");
            return;
        }
        if (TextUtils.isEmpty(mRfids)) {
            showToast("RFID不能为空!");
            return;
        }
        final DoResultDialog doResultDialog = DoResultDialog.newDialog(this)
            .setSuccessImage(R.mipmap.ic_success)
            .setWorkingText(getString(R.string.commit_binding))
            .setSuccessText(getString(R.string.commit_binding_success));

        doResultDialog.setCancelable(false);

        doResultDialog.showWorking();

        // TODO: 2017/7/26 这里标签的数据都是假的 
        MainHttp.get().bindRFID(productId, DepartmentsId,UserId, mRfids)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean hotelBean) {
                        doResultDialog.showResultAndRun(true, new Runnable() {
                            @Override
                            public void run() {
                                doResultDialog.dismiss();
                                finish();
                            }
                        }, 1000);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        doResultDialog.dismiss();
                        showToast("绑定失败," + tr.getMessage());
                    }
                });

    }

    /**
     * 初始化下拉列表
     */
    private void initView() {
        mSpecPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropSpec)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    // TODO: 2017/7/20
                    mTvSpec.setText(item);

                    specId = Integer.valueOf(specList.get(position).id);
                    initProductPopupList(specId);
                    mTvProductName.setText("");
                }
            })
            .build();
        mProductPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropProduct)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvProductName.setText(item);
                    productId = productList.get(position).getId();
                    int type = productList.get(position).type;
                    if (type == 1){
                        mItemUser.setVisibility(View.VISIBLE);
                    }else {
                        UserId = 0;
                        mItemUser.setVisibility(View.GONE);
                    }
                }
            })
            .build();

        mHospitalPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropHospital)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvHospital.setText(item);
                    HospitalId = Integer.valueOf((HospitalList.get(position).id));
                    initDepartments(HospitalId);
                    mTvDepartments.setText("");
                }
            })
            .build();

        mDepartmentsPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropDepartments)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvDepartments.setText(item);
                    DepartmentsId = Integer.valueOf(DepartmentsList.get(position).id);
                    initUser(HospitalId,DepartmentsId);
                    mTvUser.setText("");
                }
            })
            .build();
        mUserPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropUser)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvUser.setText(item);
                    UserId = Integer.valueOf(UserList .get(position).id);
                }
            })
            .build();
    }

    /**
     * 初始化规格下拉
     */
    private void initPopupList() {
        MainHttp.get().categorys()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(new OkObserver<SpecListBean>() {
                @Override
                public void onSuccess(SpecListBean bean) {
                    showOneToast(bean.msg);
                    specList = bean.data;
                    if (specList != null) {
                        String[] descNames = new String[specList.size()];
                        for (int i = 0; i < specList.size(); i++) {
                            descNames[i] = specList.get(i).title;
                        }
                        setPopupData(Constants.ITEM_TYPE.SPEC, descNames);
                    }
                }

                @Override
                public void onFailure(String message, Throwable tr) {
                    ToastUtil.show(getActivity(), message);
                }
            });
    }

    /**
     * 初始化产品下拉
     */
    private void initProductPopupList(int cateGoryId) {
        MainHttp.get().goods1(cateGoryId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(new OkObserver<ProductListBean>() {
                @Override
                public void onSuccess(ProductListBean bean) {
                    showOneToast(bean.msg);
                    productList = bean.data;

                    if (productList != null) {
                        String[] productNames = new String[productList.size()];
                        for (int i = 0; i < productList.size(); i++) {
                            productNames[i] = productList.get(i).getName();
                        }
                        setPopupData(Constants.ITEM_TYPE.PRODUCT, productNames);
                    } else {
                        setPopupData(Constants.ITEM_TYPE.PRODUCT, null);
                    }
                }

                @Override
                public void onFailure(String message, Throwable tr) {
                    ToastUtil.show(getActivity(), message);
                }
            });
    }



    /**
     * 初始化医院
     */
    private void initHospitalList() {
        MainHttp.get().gethotel(0)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(new OkObserver<HospitalBean>() {
                @Override
                public void onSuccess(HospitalBean bean) {
                    showOneToast(bean.msg);
                    HospitalList = bean.data;

                    if (HospitalList != null) {
                        String[] productNames = new String[HospitalList.size()];
                        for (int i = 0; i < HospitalList.size(); i++) {
                            productNames[i] = HospitalList.get(i).title;
                        }
                        setPopupData(Constants.ITEM_TYPE.Hospital, productNames);
                    } else {
                        setPopupData(Constants.ITEM_TYPE.Hospital, null);
                    }
                }

                @Override
                public void onFailure(String message, Throwable tr) {
                    ToastUtil.show(getActivity(), message);
                }
            });
    }

    /**
     * 初始化科室
     */
    private void initDepartments(int hotel_id) {
        MainHttp.get().getDepartments(hotel_id, 0)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(new OkObserver<DepartmentsBean>() {
                @Override
                public void onSuccess(DepartmentsBean bean) {
                    showOneToast(bean.msg);
                    DepartmentsList = bean.data;
                    if (bean.data != null) {
                        String[] productNames = new String[bean.data.size()];
                        for (int i = 0; i < bean.data.size(); i++) {
                            productNames[i] = bean.data.get(i).title;
                        }
                        setPopupData(Constants.ITEM_TYPE.departments, productNames);
                    }
                }

                @Override
                public void onFailure(String message, Throwable tr) {
                    ToastUtil.show(getActivity(), message);
                }
            });
    }

    private void initUser(int hotel_id,int office_id) {
        MainHttp.get().getUser(0, office_id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(new OkObserver<UserBean>() {
                @Override
                public void onSuccess(UserBean bean) {
                    showOneToast(bean.msg);
                    UserList = bean.data;
                    if (bean.data != null) {
                        String[] productNames = new String[bean.data.size()];
                        for (int i = 0; i < bean.data.size(); i++) {
                            productNames[i] = bean.data.get(i).name;
                        }
                        setPopupData(Constants.ITEM_TYPE.user, productNames);
                    }
                }

                @Override
                public void onFailure(String message, Throwable tr) {
                    ToastUtil.show(getActivity(), message);
                }
            });

    }

    /**
     * 设置下拉菜单数据
     */
    private void setPopupData(int item_type, String[] data) {
        switch (item_type) {
            case Constants.ITEM_TYPE.SPEC:
                mSpecPopup.setData(data, false);
                break;
            case Constants.ITEM_TYPE.PRODUCT:
                mProductPopup.setData(data, true);
                break;
            case Constants.ITEM_TYPE.Hospital:
                mHospitalPopup.setData(data, true);
                break;
            case Constants.ITEM_TYPE.departments:
                mDepartmentsPopup.setData(data, true);
                break;
            case Constants.ITEM_TYPE.user:
                mUserPopup.setData(data, false);
                break;
        }
    }
}
